<template>
    <div style="margin: 20px">
        <el-card>
            <div style="margin-bottom: 10px; display: flex">
                <el-input class="w-50 m-2" style="width: 150px" placeholder="请输入关键词" v-model="form.keywords" />
                <el-button style="margin-left: 10px" type="primary" @click="get">用户搜索</el-button>
                <el-button @click="toAdd">创建用户</el-button>
            </div>
            <el-table :data="state.tableData" :border="true" highlight-current-row>
                <el-table-column prop="id" label="ID" width="120" />
                <el-table-column prop="loginName" label="登录名" width="120" />
                <el-table-column prop="name" label="昵称" width="120" />
<!--                <el-table-column prop="password" label="密码" width="120" />-->
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="phone" label="手机号" width="120" />
<!--                <el-table-column prop="img" label="头像" width="120">-->
<!--                    <template v-slot="scope">-->
<!--                        <el-image style="width: 100px; height: 100px" :src="IMG_SERVER.IMG_SERVER + scope.row.img" />-->
<!--                        &lt;!&ndash; {{ IMG_SERVER.IMG_SERVER + scope.row.img }} &ndash;&gt;-->
<!--                    </template>-->
<!--                </el-table-column>-->
                <el-table-column prop="active" label="激活状态" width="120">
                  <template v-slot="scope">
                    <el-tag v-if="scope.row.active == '1'">已激活</el-tag>
                    <el-tag type="warning" v-else>未激活</el-tag>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="250">
                    <template v-slot="scope">
                        <el-button link size="small" @click="toRole(scope.row.id)">查看角色</el-button>
                        <el-button link size="small" @click="toEdit(scope.row)">编辑</el-button>
                        <el-popconfirm title="是否确认删除该项？" confirm-button-text="是" cancel-button-text="否"
                            @confirm="doDel(scope.row.id)">
                            <template #reference>
                                <el-button link type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button link type="primary" size="small" @click="toResource(scope.row.id)">查看权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" v-model:current-page="form.current" v-model:page-size="form.size"
                :page-sizes="[10, 20, 50]" :small="false" :disabled="false" :background="true"
                layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>
        <el-dialog v-model="roleState.visible" title="担任角色" :width="600" @close="clean">
            <el-button style="margin-left: 10px" type="primary" @click="getotherroleuser">绑定角色</el-button>
            <el-table :data="rolestate.tableData" :border="true" highlight-current-row>
                <el-table-column prop="id" label="ID" />
                <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="active" label="激活状态">
                <template v-slot="scope">
                  <el-tag v-if="scope.row.active == '1'">已激活</el-tag>
                  <el-tag type="warning" v-else>未激活</el-tag>
                </template>
              </el-table-column>
                <el-table-column fixed="right" label="Operations">
                    <template v-slot="scope">
                        <el-popconfirm title="是否确认删除该项？" confirm-button-text="是" cancel-button-text="否"
                            @confirm="doRoleDel(scope.row.id)">
                            <template #reference>
                                <el-button link type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <el-dialog v-model="resourceState.visible" title="查看权限" :width="600" @close="clean">
            <el-table :data="resourcestate.tableData" :border="true" highlight-current-row>
                <el-table-column prop="id" label="ID" />
                <el-table-column prop="name" label="资源名称" />
                <el-table-column prop="frontUrl" label="前端url" />
                <el-table-column prop="backUrl" label="后端url" />
                <el-table-column prop="type" label="资源类型" />
            </el-table>
        </el-dialog>

        <el-dialog v-model="addRoleState.visible" title="绑定角色" :width="600" @close="clean">
            <el-table :data="otherrolestate.tableData" :border="true" highlight-current-row>
                <el-table-column prop="id" label="ID" />
                <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="active" label="激活状态">
                <template v-slot="scope">
                  <el-tag v-if="scope.row.active == '1'">已激活</el-tag>
                  <el-tag type="warning" v-else>未激活</el-tag>
                </template>
              </el-table-column>
                <el-table-column fixed="right" label="Operations">
                    <template v-slot="scope">
                        <el-popconfirm title="是否确认绑定？" confirm-button-text="是" cancel-button-text="否"
                            @confirm="addroleuser(scope.row.id)">
                            <template #reference>
                                <el-button link type="danger" size="small">绑定</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <el-dialog v-model="dlgState.visible" :title="dlgState.title" :width="600" @close="clean">
            <el-form :model="dlgState.form" ref="dlg_form">
                <el-form-item label="登录名：" prop="loginName" label-width="100px">
                    <el-input v-model="dlgState.form.loginName"></el-input>
                </el-form-item>
                <el-form-item label="昵称：" prop="name" label-width="100px">
                    <el-input v-model="dlgState.form.name"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="password" label-width="100px">
                    <el-input v-model="dlgState.form.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱：" prop="email" label-width="100px">
                    <el-input v-model="dlgState.form.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号：" prop="phone" label-width="100px">
                    <el-input v-model="dlgState.form.phone"></el-input>
                </el-form-item>
                <el-form-item label="头像：" prop="img" label-width="100px">
                    <el-upload action="#" list-type="picture-card" :auto-upload="false" :multiple="false"
                        :file-list="fileList" :limit="1" :on-change="changePic" :on-remove="removePic">
                        <el-icon class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="激活状态：" prop="active" label-width="100px">
                    <el-input v-model="dlgState.form.active"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelAdd">返回</el-button>
                    <el-button type="primary" @click="doAdd" v-if="dlgState.isAdd">
                        新增
                    </el-button>
                    <el-button type="primary" @click="doEdit" v-else> 保存 </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
// import router from "@/router";
import IMG_SERVER from "../../assets/config.js";
import userApi from "@/api/user/user";
import type { UploadProps } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getCurrentInstance } from "vue";

// type definition
type user = {
    id: number;
    loginName: string;
    name: string;
    password: string;
    email: string;
    phone: string;
    img: string;
    active: number;
};
type umsRole = {
    id: number;
    name: string;
    frontUrl: string;
    backUrl: string;
    type: number;
};
type umsResource = {
    id: number;
    name: string;
    active: number;
};
// tableData
const form = reactive({
    current: 1,
    keywords: "",
    size: 10,
});
const form2 = reactive({
    current: 1,
    keywords: "",
    size: 10,
});
const form3 = reactive({
    keywords: "",
});
const roleuserremove = reactive({
    roleId: 0,
    adminId: 0,
});
const state = reactive({
    total: 0,
    tableData: [] as Array<user>,
});
const rolestate = reactive({
    total: 0,
    tableData: [] as Array<umsRole>,
});
const resourcestate = reactive({
    total: 0,
    tableData: [] as Array<umsResource>,
});
const otherrolestate = reactive({
    total: 0,
    tableData: [] as Array<umsRole>,
});
const handleSizeChange = (val: number) => {
    form.size = val;
    get();
};
const handleCurrentChange = (val: number) => {
    form.current = val;
    get();
};
const get = () => {
    userApi.get(form).then((res) => {
        if (res.data.code === 200) {
            state.tableData = res.data.data.records;
            state.total = res.data.data.total;
        }
    });
};
// 对话框
const dlg_form = ref();
const dlgState = reactive({
    visible: false,
    isAdd: true,
  title: "新增用户",
    form: {
        id: "",
        loginName: "",
        name: "",
        password: "",
        email: "",
        phone: "",
        active: "",
        imgobj: null,
    },
});

const roleState = reactive({
    visible: false,
    form: {
        id: 0,
        name: "",
        active: 0,
    },
});

const resourceState = reactive({
    visible: false,
    form: {
        id: 0,
        name: "",
        frontUrl: "",
        backUrl: "",
        type: 0,
    },
});

const addRoleState = reactive({
    visible: false,
    form: {
        id: 0,
        name: "",
        active: 0,
    },
});
const toAdd = () => {
    dlgState.isAdd = true;
    dlgState.visible = true;
    dlgState.title = "新增用户";
};
const cancelAdd = () => {
    dlgState.visible = false;
};

const doAdd = () => {
    userApi
        .add({
            //   imgobj: dlgState.form.imgobj,
            id: dlgState.form.id,
            loginName: dlgState.form.loginName,
            name: dlgState.form.name,
            password: dlgState.form.password,
            email: dlgState.form.email,
            phone: dlgState.form.phone,
            active: dlgState.form.active,
            imgobj: dlgState.form.imgobj,
        })
        .then((res) => {
            if (res.status === 200) {
                ElMessage.success("操作成功");
                get();
                dlgState.visible = false;
            }
        });
};
const clean = () => {
    dlgState.form = {
        id: "",
        loginName: "",
        name: "",
        password: "",
        email: "",
        phone: "",
        active: "",
        imgobj: null,
    };
};

const toEdit = (row: any) => {
    dlgState.form = row;
    dlgState.title = "编辑用户"
    dlgState.isAdd = false;
    dlgState.visible = true;
    console.log(editForm.form);
};
const doEdit = () => {
    userApi.update(dlgState.form).then((res) => {
        console.log(res);
        if (res.status === 200) {
            ElMessage.success("保存成功");
            get();
            dlgState.visible = false;
        }
    });
};

// 获得其他角色
const getotherroleuser = () => {
    form2.keywords = roleuserremove.adminId.toString();
    addRoleState.visible = true;
    userApi.getOtherRole(form2).then((res) => {
        if (res.data.code === 200) {
            otherrolestate.tableData = res.data.data.records;
            otherrolestate.total = res.data.data.total;
        }
    });
};

// 获取角色
const toRole = (id: number) => {
    form2.keywords = id.toString();
    roleuserremove.adminId = id;
    roleState.visible = true;
    userApi.getRoles(form2).then((res) => {
        if (res.data.code === 200) {
            rolestate.tableData = res.data.data.records;
            rolestate.total = res.data.data.total;
        }
    });
};
// 绑定角色
const addroleuser = (id: number) => {
    form2.keywords = id.toString();
    roleuserremove.roleId = id;
    roleState.visible = true;
    userApi.addroleuser(roleuserremove).then((res) => {
        if (res.data.code === 200) {
            addRoleState.visible = false;
            toRole(roleuserremove.adminId);
        }
    });
};

// 删除角色用户绑定
const doRoleDel = (id: number) => {
    roleuserremove.roleId = id;
    userApi.delroleuser(roleuserremove).then((res) => {
        if (res.status === 200) {
            ElMessage.success("删除成功");
            toRole(roleuserremove.adminId);
        }
    });
};

// 获取资源
const toResource = (id: number) => {
    form3.keywords = id.toString();
    resourceState.visible = true;
    userApi.getresources(form3).then((res) => {
        if (res.data.code === 200) {
            resourcestate.tableData = res.data.data.records;
        }
    });
};

// 项目删除
const doDel = (id: number) => {
    userApi.del(id).then((res) => {
        if (res.status === 200) {
            ElMessage.success("删除成功");
            get();
        }
    });
};
// 项目编辑
const editForm = reactive({
    form: {
        name: "",
        type: 1,
        description: "",
    },
});

// 上传头像图片
const fileList = ref([]);
const imageUrl = ref("");
const imageObj = ref({} as any);
//获取图片后，图片的改变保存
const changePic = (file: any, fileList: any) => {
    console.log(file.raw);
    dlgState.form.imgobj = file.raw;
    imageObj.value = file.raw;
    /* dlgState.form.img = file; */
};
//删除文件
const removePic = () => {
    dlgState.form.imgobj = null;
    imageObj.value = null;
    /* dlgState.form.img = null; */
};
/* const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  console.log(rawFile);
  return true;
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  console.log(uploadFile);
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  dlgState.form.img.push(uploadFile);
}; */

onMounted(() => {
    get();
});
</script>
<style lang="scss" scoped>
.tabs>.el-tabs__content {
    width: 100%;
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.tabs {
    margin: 20px;
}
</style>
